package cn.miaoyao.miaoyaoms.service;
import cn.miaoyao.miaoyaoms.entity.Notice;
import cn.miaoyao.miaoyaoms.service.impl.WebSocketServiceImpl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author: shushu
 * @Date: 2023/05/08/19:20
 * @Description:建立连接之后定时刷新数据，时间短一点进行实时刷新
 */
@Component
public class DataScheduled {

    @Autowired
    private UserService userService;
    @Autowired
    private MiaosampleService miaosampleService;
    @Autowired
    private NoticeService noticeService;

    /**
     * 实现实时刷新数据效果
     */
    @Scheduled(cron = "0/3 * * * * ? ")
    public void sendMessage(){
        CopyOnWriteArraySet<WebSocketServiceImpl> webSocketSet = WebSocketServiceImpl.getWebSocketSet();
        int userCount = userService.count();//用户实时数据
        int sampleCount=miaosampleService.count();//药材实时数据。
        LambdaQueryWrapper<Notice> notices = new LambdaQueryWrapper<>();
        notices.orderByDesc(Notice::getNoticetime).last("limit 5");//定义查询条件
        List<Notice> list1 = noticeService.list(notices);
        String noticess = JSON.toJSONString(list1);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userCount",userCount);
        map.put("miaosampleCount",sampleCount);
        map.put("notice",noticess);
        webSocketSet.forEach(item->{
            try{
                item.sendMessage(JSON.toJSONString(map));//模拟广播发送数据。
            }catch (IOException e){
                e.printStackTrace();
            }
        });
    }
}
